package handler

import (
	"strconv"

	"admin-system/internal/model"
	"admin-system/internal/service"
	"admin-system/pkg/response"
	"github.com/gin-gonic/gin"
)

// UserHandler 用户控制器
type UserHandler struct {
	userService *service.UserService
}

// NewUserHandler 创建用户控制器
func NewUserHandler() *UserHandler {
	return &UserHandler{
		userService: service.NewUserService(),
	}
}

// List 获取用户列表
func (h *UserHandler) List(c *gin.Context) {
	// 获取查询参数
	pageStr := c.DefaultQuery("page", "1")
	pageSizeStr := c.DefaultQuery("page_size", "10")
	keyword := c.Query("keyword")

	page, err := strconv.Atoi(pageStr)
	if err != nil || page < 1 {
		page = 1
	}

	pageSize, err := strconv.Atoi(pageSizeStr)
	if err != nil || pageSize < 1 || pageSize > 100 {
		pageSize = 10
	}

	// 获取用户列表
	users, total, err := h.userService.ListUsers(page, pageSize, keyword)
	if err != nil {
		response.ServerError(c, "获取用户列表失败: "+err.Error())
		return
	}

	// 转换为响应格式
	var userResponses []model.UserResponse
	for _, user := range users {
		var roleSimples []model.RoleSimple
		for _, role := range user.Roles {
			roleSimples = append(roleSimples, model.RoleSimple{
				ID:   role.ID,
				Name: role.Name,
			})
		}

		userResponses = append(userResponses, model.UserResponse{
			ID:        user.ID,
			Username:  user.Username,
			Name:      user.Name,
			Email:     user.Email,
			Status:    user.Status,
			CreatedAt: user.CreatedAt,
			UpdatedAt: user.UpdatedAt,
			Roles:     roleSimples,
		})
	}

	response.Pagination(c, userResponses, total, page, pageSize)
}

// Get 获取用户详情
func (h *UserHandler) Get(c *gin.Context) {
	// 获取用户ID参数
	userIDStr := c.Param("id")
	userID, err := strconv.ParseUint(userIDStr, 10, 32)
	if err != nil {
		response.BadRequest(c, "无效的用户ID")
		return
	}

	// 获取用户信息
	user, err := h.userService.GetUserByID(uint(userID))
	if err != nil {
		response.NotFound(c, "用户不存在")
		return
	}

	response.Success(c, user)
}

// Create 创建用户
func (h *UserHandler) Create(c *gin.Context) {
	var req model.UserCreateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "请求参数错误: "+err.Error())
		return
	}

	// 创建用户
	user, err := h.userService.CreateUser(&req)
	if err != nil {
		response.Error(c, 400, err.Error())
		return
	}

	response.Success(c, user)
}

// Update 更新用户
func (h *UserHandler) Update(c *gin.Context) {
	// 获取用户ID参数
	userIDStr := c.Param("id")
	userID, err := strconv.ParseUint(userIDStr, 10, 32)
	if err != nil {
		response.BadRequest(c, "无效的用户ID")
		return
	}

	var req model.UserUpdateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "请求参数错误: "+err.Error())
		return
	}

	// 更新用户
	err = h.userService.UpdateUser(uint(userID), &req)
	if err != nil {
		response.Error(c, 400, err.Error())
		return
	}

	response.Success(c, gin.H{
		"message": "用户更新成功",
	})
}

// Delete 删除用户
func (h *UserHandler) Delete(c *gin.Context) {
	// 获取用户ID参数
	userIDStr := c.Param("id")
	userID, err := strconv.ParseUint(userIDStr, 10, 32)
	if err != nil {
		response.BadRequest(c, "无效的用户ID")
		return
	}

	// 检查是否为当前用户
	currentUserIDInterface, exists := c.Get("userID")
	if exists {
		if currentUserID, ok := currentUserIDInterface.(uint); ok && currentUserID == uint(userID) {
			response.BadRequest(c, "不能删除自己")
			return
		}
	}

	// 删除用户
	err = h.userService.DeleteUser(uint(userID))
	if err != nil {
		response.Error(c, 400, err.Error())
		return
	}

	response.Success(c, gin.H{
		"message": "用户删除成功",
	})
}
